package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.SysLog;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

@WebServlet("/sysLog/*")
public class SysLogServlet extends BaseServlet {

    //查询/模糊查询(需要分页)
    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String stime = req.getParameter("stime");
        req.setAttribute("stime",stime);
        //获取分页参数
        String pageNum = req.getParameter("pageNum");
        String pageSize = req.getParameter("pageSize");
        List<SysLog> list= sysLogService.findAll(pageNum, pageSize,stime);
        PageInfo<SysLog> page = new PageInfo<>(list);
        //把分页对象放入作用域
        req.setAttribute("page", page);
        //跳转到展示数据界面
        req.getRequestDispatcher("/pages/syslog-list.jsp").forward(req, resp);

    }

    //删除方法
    private void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //1、获取ids
        String ids = req.getParameter("ids");
        //2、调用service
        boolean flag = sysLogService.deleteByIds(ids);
        if (flag) {
            //3、再次调用findAll
            findAll(req, resp);
        } else {
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }
    }

    //下载导出excel
    private void download(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String stime = req.getParameter("stime");
        //获取分页参数
        String pageNum = req.getParameter("pageNum");

        String pageSize = req.getParameter("pageSize");
        //返回的数据类型为文件xlsx类型
        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = new String("日志文件.xlsx".getBytes(),"iso8859-1");
        resp.addHeader("Content-Disposition","attachment;fileName="+fileName);
        //获取当前页
        ByteArrayOutputStream os = sysLogService.getReport(pageNum, pageSize, stime);
        //获取产生响应的流对象
        ServletOutputStream sos = resp.getOutputStream();
        //将数据从原始的字节流对象中提取出来写入到servlet对应的输出流中
        os.writeTo(sos);
        //将输出流刷新
        sos.flush();
        os.close();


    }
}